import { createRouter, createWebHistory } from 'vue-router'

const router = createRouter({
    history: createWebHistory(import.meta.env.BASE_URL),
    routes: [
        {
            path: '/',
            name: 'home',
            component: () => import('../views/Home.vue')
        },
        {
            path: '/login',
            name: 'login',
            component: () => import('../views/Login.vue')
        },
        {
            path: '/students',
            name: 'students',
            component: () => import('../views/Students.vue'),
            meta: { requiresAuth: true, role: 'teacher' }
        },
        {
            path: '/classes',
            name: 'classes',
            component: () => import('../views/Classes.vue'),
            meta: { requiresAuth: true, role: 'teacher' }
        },
        {
            path: '/departments',
            name: 'departments',
            component: () => import('../views/Departments.vue'),
            meta: { requiresAuth: true, role: 'teacher' }
        },
        {
            path: '/punishments',
            name: 'punishments',
            component: () => import('../views/Punishments.vue'),
            meta: { requiresAuth: true, role: 'teacher' }
        },
        {
            path: '/rewards',
            name: 'rewards',
            component: () => import('../views/Rewards.vue'),
            meta: { requiresAuth: true, role: 'teacher' }
        },
        {
            path: '/ocr',
            name: 'ocr',
            component: () => import('../views/OCR.vue'),
            meta: { requiresAuth: true }
        },
        {
            path: '/my-rewards',
            name: 'myRewards',
            component: () => import('../views/MyRewards.vue'),
            meta: { requiresAuth: true, role: 'student' }
        },
        {
            path: '/my-punishments',
            name: 'myPunishments',
            component: () => import('../views/MyPunishments.vue'),
            meta: { requiresAuth: true, role: 'student' }
        }
    ]
})

// 修改导航守卫
router.beforeEach((to, from, next) => {
    // 从 store 中获取 token 和用户信息
    const token = localStorage.getItem('token')
    const userInfo = JSON.parse(localStorage.getItem('userInfo'))

    // 需要认证的路由
    if (to.meta.requiresAuth) {
        if (!token) {
            // 没有token，跳转到登录页
            next({ name: 'login' })
        } else if (to.meta.role && to.meta.role !== userInfo?.role) {
            // 角色不匹配，跳转到对应角色的首页
            next({ name: userInfo?.role === 'teacher' ? 'students' : 'myRewards' })
        } else {
            next()
        }
    } else {
        // 已登录用户访问登录页，重定向到首页
        if (to.name === 'login' && token) {
            next({ name: 'home' })
        } else {
            next()
        }
    }
})

export default router